package com.xq.wuer.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class WuerApi {


    private static final String BASE_URL="https://cmapi.dsbox.net/ai-api/";
    private static String GET_LIST = BASE_URL+"product/work/list?width=400&height=800&type=%s&hot=0&next=%s&hotPos=%s&sort=1&limit=6&mode=2&ownerId=&topTypeId=100000";//type 分类名称   next默认0
    private static String GET_DIY = BASE_URL+"product/work/diy?model=Mi 6&width=750&height=1500&uwid=%s&wcid=&size=0&excode=&partnerId=&productId=10000";//uwid 商品id

    public JSONObject getDiy(String id){
        JSONObject jsonObject = get(String.format(GET_DIY, id), null);
        return jsonObject;
    }


    public JSONObject getList(String type,String next,String hotPos){
        JSONObject jsonObject = get(String.format(GET_LIST, type, next,hotPos), null);
        return jsonObject;
    }


    private JSONObject get(String url, Map<String,String> param){
        try {
            //获取请求连接
//            System.out.println(url);
            Connection con = Jsoup.connect(url)
                    .headers(getHeaders())
                    .ignoreContentType(true);
//                    .data(param);

            JSONObject jsonObject = JSON.parseObject(con.get().text());
            return jsonObject;

        }catch (IOException e){
            System.out.println("获取信息异常"+e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    private Map<String,String> getHeaders(){
        Map<String,String> headers = new HashMap<>();
        headers.put("charset","utf-8");
        headers.put("Accept-Language","gzip");
        headers.put("fid","0");
        headers.put("Referer","https://servicewechat.com/wx5ed31a71d75fd231/135/page-frame.html");
        headers.put("content-type","application/json;charset=utf-8");
        headers.put("model","Mi%206");
        headers.put("versioncode","227");
        headers.put("token","ad6eded280e69b765d77997b15f9174b");
        headers.put("cid","0");
        headers.put("User-Agent","Mozilla/5.0 (Linux; Android 8.0.0; MI 6 Build/OPR1.170623.027; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/68.0.3440.91 Mobile Safari/537.36 MicroMessenger/6.7.2.1340(0x2607023A) NetType/4G Language/zh_CN");
        headers.put("Host","cmapi.dsbox.net");
        headers.put("Connection","keep-Alive");

        return headers;
    }

    /**
     * 每个登陆后的请求都需要下面这两个参数，所以把他单独封装成了一个方法。
     * @param token
     * @param userId
     * @return
     */
    private Map<String,String> getParam(String token,String userId){
        Map<String,String> param = new HashMap<>();
        param.put("userId",userId);
        param.put("accessToken",token);
        return param;
    }
}
